package com.carp.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.carp.entity.CarpFile;
import com.carp.service.CarpFileService;
import com.carp.service.CarpUserService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@RestController
@RequestMapping("/file")
public class FileController {
    @Value("${files.upload.path}")
    private String fileUploadPath;


    @Resource
    private CarpFileService carpFileService;

    /**
     * 上传文件upload
     */

    @PostMapping("/upload")
    public String toUpload(@RequestParam("file") MultipartFile file) throws IOException {

        System.out.println(file);

        //获取原始文件名,类型,大小
        String originalFilename = file.getOriginalFilename();
        String fileType = FileUtil.extName(originalFilename);
        long size = file.getSize();

        //先储存在磁盘
        File file1 = new File(fileUploadPath);
        //判断文件是否存在,不存在则创建文件夹
        if (!file1.exists()){
            file1.mkdirs();
        }

        //使用uuid,定义一个唯一标识码
        String uuid = IdUtil.fastSimpleUUID();
        String fileUuid = uuid + StrUtil.DOT + fileType;
        //生成 uuid.fileType  的文件
        File file2 = new File(fileUploadPath + fileUuid);
        //写入磁盘
        file.transferTo(file2);
        //获取当前上传文件的md5
        String fileMd5 = SecureUtil.md5(file2);

        //使用当前上传文件md5取数据库查询,有则直接使用数据库中的url,没有则添加操作
        CarpFile carpFile = carpFileService.selectByMd5(fileMd5);

        if (carpFile != null){
            //删除刚才创建的文件,使用从数据库的url路径
            file2.delete();
            return carpFile.getFileUrl();
        }

        //添加操作
        //设置文件路径
        String url = "http://localhost:8188/file/"+fileUuid;

        //创建一个CarpFile对象
        CarpFile carpFile1 = new CarpFile();
        carpFile1.setFileUrl(url);
        carpFile1.setFileMd5(fileMd5);

        //执行插入操作
        carpFileService.insertFile(carpFile1);

        return url;
    }

    /**
     * bytes字节流返回图片
     */
    @RequestMapping(value = "/{images}",produces = MediaType.IMAGE_JPEG_VALUE)
    public byte[] toTest(@PathVariable("images") String img) throws IOException {
        File file = new File("E:/Test/"+img);
        FileInputStream inputStream = new FileInputStream(file);
        byte[] bytes = new byte[inputStream.available()];
        inputStream.read(bytes, 0, inputStream.available());
        return bytes;
    }



}
